import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync

from users.models import CommunicationModel
from users.utils import redis_conn

# class ChatConsumer(WebsocketConsumer):
    # def connect(self):
    #     self.accept()
    #
    # def disconnect(self, close_code):
    #     pass
    #
    # def receive(self, text_data):
    #     text_data_json = json.loads(text_data)
    #     message = text_data_json['message']
    #
    #     self.send(text_data=json.dumps({
    #         'message': message
    #     }))


# 聊天室
class ChatConsumer(WebsocketConsumer):
    # 连接
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    # 断开
    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # 从Websocket接收消息
    # Receive message from WebSocket
    def receive(self, text_data):
        # print("web",text_data)
        text_data = json.loads(text_data)
        text_data["type"] = "chat_message"

        # 发送消息到房间组
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            text_data
        )

    # 接收房间组消息
    # Receive message from room group
    def chat_message(self, data):
        # Send message to WebSocket
        self.send(text_data=json.dumps(data))

# 用户在线
class UserChatConsumer(WebsocketConsumer):
    redis = redis_conn()

    # 连接
    def connect(self):
        name = self.scope['url_route']['kwargs']['id']
        user_id = name.split("_")[0]
        user_type = name.split("_")[1]

        # print(name,user_id,user_type)
        comm_list = CommunicationModel.objects.filter(is_delete=False).all()
        if not user_type:  # 用户
            comm_list = comm_list.filter(user_id=user_id).all()
        else:
            comm_list = comm_list.filter(shops_id=user_id).all()

        self.room_name = []
        for i in comm_list:
            self.room_name.append(i.id)
            self.room_group_name = 'chat_%s' % i.id

            # Join room group
            async_to_sync(self.channel_layer.group_add)(
                self.room_group_name,
                self.channel_name
            )

        self.accept()

    # 断开
    def disconnect(self, close_code):
        for i in self.room_name:
            self.room_group_name = 'chat_%s' % i
            # Leave room group
            async_to_sync(self.channel_layer.group_discard)(
                self.room_group_name,
                self.channel_name
            )

    # 从Websocket接收消息
    # Receive message from WebSocket
    def receive(self, text_data):

        # print("web",text_data)
        text_data = json.loads(text_data)
        text_data["type"] = "chat_message"

        self.room_group_name = 'chat_%s' % text_data["chat_id"]

        # 发送消息到房间组
        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            text_data
        )

    # 接收房间组消息
    # Receive message from room group
    def chat_message(self, data):
        # Send message to WebSocket
        self.send(text_data=json.dumps(data))